﻿// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍
namespace Manhua2.Pages
{
    using Manhua2.Common;
    using Manhua2.Helper;
    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.Storage;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.UI.Xaml.Navigation;
    using WinRTXamlToolkit.Async;
    using WinRTXamlToolkit.Imaging;

    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class SettingPage : Page, INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChaned(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
        #endregion

        public bool LeftToRight 
        {
            get { return Global.ClientOption.L2R; }
            set { Global.ClientOption.L2R = value; }
        }


        private AsyncAutoResetEvent _triangleUpdateRequired = new AsyncAutoResetEvent();
        private bool _isLoaded = false;
        private SolidColorBrush backgroundBrush;

        private double s, v;

        public SettingPage()
        {
            this.InitializeComponent();

            this.DataContext = this;

            this.Loaded += async (sender, e) => 
            {
                this.cboProvider.SelectedItem =
                    this.cboProvider.Items.Where(
                    k => ((ComboBoxItem)k).Tag.ToString() == Global.ClientOption.DefaultProviderName).FirstOrDefault();
                var style = (Windows.UI.Xaml.Style)App.Current.Resources.MergedDictionaries[0]["LayoutRootStyle"];
                var setter = (Windows.UI.Xaml.Setter)style.Setters[0];
                this.backgroundBrush = ((SolidColorBrush)setter.Value);  


                // 初始化页面时 将默认颜色转换成hsv格式， 显示到窗体中
                var hsv = this.backgroundBrush.Color.ToHsv();
                this.hueRing.Value = hsv.H;
                this.s = hsv.S;
                this.v = hsv.V;

                _isLoaded = true;
                RunTriangleUpdaterAsync();

                // 初始化时需要绘制三角形颜色选取器
                await this.RenderTriangle();

                this.hueRing.ValueChanged += this.hueRing_ValueChanged;
                this.trianglePicker.ValueChanged += this.trianglePicker_ValueChanged;
            };

            this.Unloaded += (sender, e) => 
            {
                this.hueRing.ValueChanged -= this.hueRing_ValueChanged;
                this.trianglePicker.ValueChanged -= this.trianglePicker_ValueChanged;

                _isLoaded = false;
                _triangleUpdateRequired.Set();
            };
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。Parameter
        /// 属性通常用于配置页。</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("comic");
                var size = await this.GetFolderSize(folder);

                this.txtCache.Text = string.Format(
                    "在线阅读缓存  {0}MB",
                    Math.Round(size / 1024.0 / 1024.0, 2));
            }
            catch
            {
            }

            this.btnClear.Content = "清除缓存";
            this.btnClear.Click += btnClear_Click;
        }

        protected async override void OnNavigatedFrom(NavigationEventArgs e)
        {
            await Global.SaveSettingsAsync();
            base.OnNavigatedFrom(e);
        }

        private async void RunTriangleUpdaterAsync()
        {
            do
            {
                await _triangleUpdateRequired.WaitAsync();

                if (_isLoaded)
                {
                    await this.RenderTriangle();                                        
                    this.SetBkColor();
                }
            }
            while (_isLoaded);
        }

        private async void btnClear_Click(object sender, RoutedEventArgs e)
        {
            bool isFailed = false;

            try
            {
                var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("comic");
                await folder.DeleteAsync();
                this.txtCache.Text = "在线阅读缓存  0.0MB";
            }
            catch (Exception)
            {
                isFailed = true;
            }

            if (isFailed)
                await MethodHelper.ShowMessageDialog("删除失败, 建议您退出下次启动程序时直接执行清除缓存功能。");
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (this.Frame.CanGoBack)
                this.Frame.GoBack();
            else
                this.Frame.Navigate(typeof(MainPage));
        }

        private async Task<ulong> GetFolderSize(StorageFolder folder)
        {
            ulong size = 0;

            try
            {
                var files = await folder.GetFilesAsync();
                foreach (var file in files)
                {
                    try
                    {
                        var prop = await file.GetBasicPropertiesAsync();
                        size += prop.Size;
                    }
                    catch
                    {
                    }
                }

                var folders = await folder.GetFoldersAsync();
                foreach (var f in folders)
                {
                    size += await this.GetFolderSize(f);
                }
            }
            catch
            {
            }

            return size;
        }

        private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {

        }

        private void hueRing_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            _triangleUpdateRequired.Set();
        }

        private void trianglePicker_ValueChanged(object sender, EventArgs e)
        {            
            this.SetBkColor();
        }

        private void SetBkColor()
        {
            this.s = 1 - this.trianglePicker.X;
            this.v = 1 - this.trianglePicker.Y;

            this.backgroundBrush.Color = ColorExtensions.FromHsv(
                hueRing.Value,
                this.s,
                this.v);

            Global.ClientOption.Background = this.backgroundBrush.Color;
        }

        private async Task RenderTriangle()
        {
            WriteableBitmap wb = triangleBrush.ImageSource as WriteableBitmap;
            if (wb == null)
            {
                wb = new WriteableBitmap(
                                (int)trianglePicker.ActualWidth,
                                (int)trianglePicker.ActualHeight);

                triangleBrush.ImageSource = wb;
            }

            await wb.RenderColorPickerSaturationValueTriangleAsync(hueRing.Value);
        }

        private void cboProvider_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.cboProvider.SelectedItem != null)
            {
                Global.ClientOption.DefaultProviderName = ((ComboBoxItem)this.cboProvider.SelectedItem).Tag.ToString();
            }
        }
        
    }
}
